package com.zhangmeng.service.impl;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.zhangmeng.service.ConnManager;
import com.zhangmeng.service.Connection;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author zm
 * @date 2025/2/27 14:49
 * @version: 1.0
 */
public class ConnManagerImpl implements ConnManager {

    private final Log log = LogFactory.get();

    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    private Map<Integer, Connection> connections = new HashMap<>(); //管理的连接信息

    @Override
    public void Add(Connection conn) {
        //保护共享资源Map 加写锁
        rwl.writeLock().lock(); // 获取写锁
        try {
            log.info("connection add to ConnManager successfully: conn num = {}", connections.size());
            //将conn连接添加到ConnMananger中
            this.connections.put(conn.GetConnID(), conn);
        } finally {
            rwl.writeLock().unlock(); // 释放写锁
        }
    }

    @Override
    public void Remove(Connection conn) {
        //保护共享资源Map 加写锁
        rwl.writeLock().lock(); // 获取写锁
        try {
            //删除连接信息
            this.connections.remove(conn.GetConnID());
            log.info("connection Remove ConnID=",conn.GetConnID(), " successfully: conn num = ", connections.size());
        } finally {
            rwl.writeLock().unlock(); // 释放写锁
        }
    }

    @Override
    public Connection Get(int connID) {

        //保护共享资源Map 加读锁
        rwl.readLock().lock(); // 获取读锁
        try {
            //获取指定连接信息
            return this.connections.get(connID);
        } finally {
            rwl.readLock().unlock(); // 释放读锁
        }
    }

    @Override
    public int Len() {
        return this.connections.size();
    }

    @Override
    public void ClearConn() {
        //保护共享资源Map 加写锁
        rwl.writeLock().lock(); // 获取写锁
        try {
            //清空连接信息
            this.connections.clear();
        } finally {
            rwl.writeLock().unlock(); // 释放写锁
        }
    }
}
